Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

340
Visualizações
How to stop game, after the player wins in [XO game] with react?

I create this game with React. I want to finish the game after the first player wins an XO game in React. In other words: After the first player wins, the next player can not continue the game and the game ends. this is my code:

function App() {
    const [state,setstate]=useState({
        player: "CIRCLE",
        positions: [
            'EMPTY', 'EMPTY','EMPTY',
            'EMPTY', 'EMPTY','EMPTY',
            'EMPTY', 'EMPTY','EMPTY',
        ]
    })

   
    // mark X or O
    function takeTurn(position) {
        const positions=[...state.positions];
        
        positions[position] = state.player;

        setstate({
            player:state.player === 'CIRCLE' ? 'CROSS' : 'CIRCLE',
            positions,
        })
    }


    return(
        <div >
            <div className="player"> Player :  [{state.player}] </div>
          
            <div  className="total">
                <Square position={0}  value={state.positions[0]} takeTurn={takeTurn}  />            
                <Square position={1}  value={state.positions[1]} takeTurn={takeTurn}  />            
                <Square position={2}  value={state.positions[2]} takeTurn={takeTurn}   />            
                <Square position={3}  value={state.positions[3]} takeTurn={takeTurn}  />            
                <Square position={4}  value={state.positions[4]} takeTurn={takeTurn}  />            
                <Square position={5}  value={state.positions[5]} takeTurn={takeTurn}  />            
                <Square position={6}  value={state.positions[6]} takeTurn={takeTurn}  />            
                <Square position={7}  value={state.positions[7]} takeTurn={takeTurn}  />            
                <Square position={8}  value={state.positions[8]} takeTurn={takeTurn}  /> 
            </div>
            <div className="caption">
                Winner = &nbsp; {winner && <Result winner={winner} />}    
            </div>
            <div className="reset"><button onClick={reset} >Reset</button></div>
        </div>
    )
}

export default App;
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

So it looks like you need a few things.

  • A way to determine if there is a winner
  • The definition of the winner variable

You could add the winner to your state, and change the winner calculation line to:

Winner = &nbsp; {state.winner && <Result winner={state.winner} />}

To calculate the winner, the app needs to know the winning lines and check if the same symbol is in all 3:

function calculateWinner(positions) {
    const lines = [
        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8],
        [0, 3, 6],
        [1, 4, 7],
        [2, 5, 8],
        [0, 4, 8],
        [2, 4, 6]
    ];

    for (let i = 0; i < lines.length; i++) {
        const [a, b, c] = lines[i];
        if (positions[a] && positions[a] === positions[b] && positions[a] === positions[c]) {
            return positions[a];
        }
    }
    return null;
}

You can then use this in your takeTurn function to return early if there is already a winner and therefore not update the board, and also to recalculate if there is a winner each time:

function takeTurn(position) {
    const positions = [...state.positions];
    if (!state.winners) return;

    positions[position] = state.player;

    setstate({
        player: state.player === 'CIRCLE' ? 'CROSS' : 'CIRCLE',
        positions,
        winner: calculateWinner(positions)
    });
}

With functional components, it is also a best practice to not have a single state object, but to have one for each property you would usually have. This makes it easier to set and manage each on properly, so you may consider changing your state code to:

const [player, setPlayer] = useState('CIRCLE');
const [positions, setPositions = useState([
        'EMPTY', 'EMPTY','EMPTY',
        'EMPTY', 'EMPTY','EMPTY',
        'EMPTY', 'EMPTY','EMPTY',
      ]);
const [winner, setWinner] = useState(null);

and update the setter code accordingly.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda